package com.tusuo.stds.ui.question;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.text.TextUtils;

import com.hannesdorfmann.mosby.mvp.MvpBasePresenter;
import com.tusuo.stds.Constants;
import com.tusuo.stds.MyApp;
import com.tusuo.stds.R;
import com.tusuo.stds.di.DaggerScope;
import com.tusuo.stds.di.Injector;
import com.tusuo.stds.rest.ApiHelper;
import com.tusuo.stds.rest.ApiResult;
import com.tusuo.stds.rest.LevelDetail;
import com.tusuo.stds.rest.Question;
import com.tusuo.stds.ui.level.LevelResultActivity_;
import com.tusuo.stds.util.DESedeUtil;
import com.tusuo.stds.util.Utils;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.inject.Inject;

import autodagger.AutoComponent;
import autodagger.AutoInjector;
import rx.Subscriber;
import timber.log.Timber;

import static com.tusuo.stds.Constants.ACTIVITY_REQUEST_GENERAL;

/**
 * @author J.Huang
 * @version 1.0
 *
 */
@AutoComponent(
        dependencies = MyApp.class
)
@AutoInjector
@DaggerScope(QuestionPresenter.class)
class QuestionPresenter extends MvpBasePresenter<QuestionView>
                            implements ISwipeablePresenter {

    @Inject
    ApiHelper mApiHelper;
    @Inject
    SharedPreferences mSharedPref;

    private Activity mActivity;
    private String mErrMsgServer;

    private Subscriber<ApiResult> mSubmitAnswerSubscriber = null;

    private LevelDetail mLevelDetail = null;
    private int mCurrentIndex;
    private int mLatestIndex;
    private List<Question> mQuestionHistoryList;
    private List<HashSet<Integer>> mUserChoiceList;
    private Question mCurrentQuestion;

    private long mLastTimeMillis;
    private boolean mFirstAnswer;
    private boolean mFinalQuestion;

    QuestionPresenter(Activity activity, LevelDetail levelDetail, boolean firstAnswer) {
        mActivity = activity;
        mErrMsgServer = mActivity.getResources().getString(R.string.err_msg_server);
        mLevelDetail = levelDetail;

        mLatestIndex = 0;
        mCurrentIndex = 0;

        mFirstAnswer = firstAnswer; // 是否首次做题

        mQuestionHistoryList = new ArrayList<>();
        mUserChoiceList = new ArrayList<>();

        if (mLevelDetail.QuestionList.size() < 1) {
            mCurrentQuestion = null;
            return;
        }

        mCurrentQuestion = mLevelDetail.QuestionList.get(mCurrentIndex);


        // 获取开始做题的时间
        mLastTimeMillis = System.currentTimeMillis();

        mFinalQuestion = false;

        Injector.initQuestionPresenterComponent().inject(this);
    }

    @Override
    public void attachView(QuestionView view) {
        super.attachView(view);
        if (getView() != null) {
            getView().initFirst();
            if (mSharedPref == null) {
                mSharedPref = PreferenceManager.getDefaultSharedPreferences(mActivity);
            }
            getView().setSecretKey(DESedeUtil.getSecretKey(mSharedPref.getString(Constants.KEY_COOKIE, "")));
        }
    }

    @Override
    public void detachView(boolean retainInstance) {
        if (mSubmitAnswerSubscriber != null) {
            mSubmitAnswerSubscriber.unsubscribe();
            mSubmitAnswerSubscriber = null;
        }
        mQuestionHistoryList.clear();
        mQuestionHistoryList = null;
        mUserChoiceList.clear();
        mUserChoiceList = null;
        mCurrentQuestion = null;
        mLevelDetail = null;

        super.detachView(retainInstance);
    }

    void initData() {
        if (getView() != null) {
            if (mCurrentQuestion != null) {
                getView().setCurrentQuestion(mCurrentIndex, mCurrentQuestion,
                        mCurrentIndex < mQuestionHistoryList.size(), null);
            } else {
                getView().showNoQuestionTip();
            }
        }
    }

    public void submitAnswer(String answerContent,int levelId,int questionId,long elapseSec,boolean isFinal) {
        mFinalQuestion = isFinal;
        mSubmitAnswerSubscriber = new SubmitAnswerSubscriber(answerContent, levelId, questionId, elapseSec, isFinal);
        mApiHelper.submitAnswer(mSubmitAnswerSubscriber,
                levelId,
                questionId,
                elapseSec,
                answerContent);
    }

    boolean toNextNewQuestion(String answerContent) {
//                              HashSet<Integer> userChoices) {
        // 题目是否已经加载完成
        if (TextUtils.isEmpty(answerContent) || mCurrentQuestion == null) {
            return false;
        }

        mLatestIndex++;

        long now = System.currentTimeMillis();
        long elapseSec = (now - mLastTimeMillis) / 1000;
        mLastTimeMillis = now;

//        mSubmitAnswerSubscriber = new SubmitAnswerSubscriber();
        mApiHelper.submitAnswer(mSubmitAnswerSubscriber,
                mLevelDetail.Id,
                mCurrentQuestion.Id,
                elapseSec,
                answerContent);
//                userAnswer.toString());

        // 做完最后一题
        if (mLatestIndex >= mLevelDetail.QuestionList.size()) {
            mFinalQuestion = true;

            return true;
        }

//        mUserChoiceList.add(userChoices);
        mQuestionHistoryList.add(mCurrentQuestion);
        mCurrentIndex++;
        mCurrentQuestion = mLevelDetail.QuestionList.get(mCurrentIndex);

        if (getView() != null) {
            getView().setCurrentQuestion(mCurrentIndex, mCurrentQuestion,
                    mCurrentIndex < mQuestionHistoryList.size(), null);

            if (mFirstAnswer) {
                SharedPreferences.Editor editor = mSharedPref.edit();
                editor.putBoolean("firstAnswer", false);
                editor.apply();

                mActivity.startActivity(new Intent(mActivity, QuestionTipActivity_.class));

                mFirstAnswer = false;
            }
        }

        return true;
    }

    @Override
    public void toNextOldQuestion() {
        // 题目是否已经加载完成
        if (mLevelDetail == null) {
            return;
        }

        // 不能超过正在做的一题
        if (mCurrentIndex >= mLatestIndex) {
            return;
        }

//        Utils.UI.showToastShort("加载下一题...");

        mCurrentIndex++;
        mCurrentQuestion = mLevelDetail.QuestionList.get(mCurrentIndex);

        Set<Integer> choices;

        if (mCurrentIndex >= mUserChoiceList.size()) {
            choices = null;
        } else {
            choices = mUserChoiceList.get(mCurrentIndex);
        }

        if (getView() != null) {
            getView().setCurrentQuestion(mCurrentIndex,
                    mCurrentQuestion,
                    mCurrentIndex < mQuestionHistoryList.size(),
                    choices);
        }
    }

    @Override
    public void toLastQuestion() {
        // 题目是否已经加载完成
        if (mLevelDetail == null) {
            return;
        }

        // 从第2题开始，才能回看
        if (mCurrentIndex <= 0) {
            return;
        }

//        Utils.UI.showToastShort("加载上一题...");

        mCurrentIndex--;
        mCurrentQuestion = mLevelDetail.QuestionList.get(mCurrentIndex);
        if (getView() != null) {
            getView().setCurrentQuestion(mCurrentIndex,
                    mCurrentQuestion,
                    mCurrentIndex < mQuestionHistoryList.size(),
                    mUserChoiceList.get(mCurrentIndex));
        }
    }

    private class SubmitAnswerSubscriber extends Subscriber<ApiResult> {

        private int questionId;
        private long elapseSec;
        private boolean isFinal;
        private int levelId;
        private String answerContent;

        SubmitAnswerSubscriber(String answerContent, int levelId, int questionId, long elapseSec, boolean isFinal) {
            this.answerContent = answerContent;
            this.levelId = levelId;
            this.questionId = questionId;
            this.elapseSec = elapseSec;
            this.isFinal = isFinal;
        }

        @Override
        public void onCompleted() {
            if (mFinalQuestion) {
                if (getView() != null) {
                    getView().toResultActivity(mLevelDetail);
                }

            }
        }

        @Override
        public void onError(Throwable e) {
            Utils.UI.showToastShort("提交答案失败！请联系管理员或稍候再试");
            if (getView() != null) {
                getView().requestSubmitQuestion(questionId,elapseSec,isFinal,levelId,answerContent);
            }
        }

        @Override
        public void onNext(final ApiResult result) {
            if (getView() != null) {
                getView().toNextQuestion();
            }
        }
    }
}
